#pragma once
#include <iostream>
#include <unistd.h>
#include <string>
#include <map>
#include <vector>
#include <sys/resource.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <fcntl.h>
#include "../comm/Log.hpp"
#include "../comm/util.hpp"

namespace ns_runner
{
    using namespace ns_Log;
    using namespace ns_util;
    class runner
    {
    public:
        runner() {}
        ~runner() {}
        // 限制资源接口
        static void SetRunLimit(int _cpu_limit, int _mem_limit)
        {
            // 限制时间资源
            struct rlimit cpu_limit;
            cpu_limit.rlim_max = RLIM_INFINITY;
            cpu_limit.rlim_cur = _cpu_limit;
            setrlimit(RLIMIT_CPU, &cpu_limit);

            // 限制空间资源
            struct rlimit mem_limit;
            mem_limit.rlim_max = RLIM_INFINITY;
            mem_limit.rlim_cur = 1024*_mem_limit;//kB
            setrlimit(RLIMIT_AS, &mem_limit);
        }

        // 返回值代表状态，小于0表示内部出错，等于0正常，大于0运行出错
        static int Run(const std::string &file_name, int _cpu_limit, int _mem_limit)
        {
            std::string _excute = Pathutil::Exe(file_name);
            std::string _stdin = Pathutil::Stdin(file_name);
            std::string _stdout = Pathutil::Stdout(file_name);
            std::string _stderr = Pathutil::Stderr(file_name);

            umask(0);
            int _stdin_fd = open(_stdin.c_str(), O_CREAT | O_RDONLY, 0644);
            int _stdout_fd = open(_stdout.c_str(), O_CREAT | O_WRONLY, 0644);
            int _stderr_fd = open(_stderr.c_str(), O_CREAT | O_WRONLY, 0644);

            if (_stdin_fd < 0 || _stdout_fd < 0 || _stderr_fd < 0)
            {
                LOG(Error) << "运行打开标准文件失败" << "\n";
                return -1;
            }

            pid_t pid = fork();
            if (pid < 0)
            {
                LOG(Error) << "创建子进程失败" << "\n";
                close(_stdin_fd);
                close(_stdout_fd);
                close(_stderr_fd);
                return -1;
            }
            else if (pid == 0)
            {
                dup2(_stdin_fd, 0);
                dup2(_stdout_fd, 1);
                dup2(_stderr_fd, 2);

                SetRunLimit(_cpu_limit, _mem_limit);
                execl(_excute.c_str(), _excute.c_str(), nullptr);
                exit(1);
            }
            int status = 0;
            waitpid(pid, &status, 0);
            LOG(Info)<<"运行完毕, info: "<<(status & 0x7f)<<"\n";
            close(_stdin_fd);
            close(_stdout_fd);
            close(_stderr_fd);
            return status & 0x7f;
        }
    };
}